#include "StdAfx.h"
#include "PasswordMgrUiHandler.h"
#include "..\Common\CategoryDlg.h"
#include "..\DataManager\CategoryManager.h"
#include "..\Common\Preferences.h"
#include "..\Common\pkmpmsgbox.h"
#include "..\MainDlg.h"
#include "AddAccountDlg.h"
#include "PasswordDlg.h"
#include "Util\StrUtil.h"
#include "Util\PwUtil.h"
#include "Util\AppUtil.h"
#include "Util\WinUtil.h"
#include "Util\SendKeysEx.h"
#include "GetRandRomDlg.h"
#include "..\Common\Ini2.h"


PW_GEN_SETTINGS_EX CPasswordMgrUiHandler::m_pgsAutoProfile;

BOOL CPwSafeAppRI::GenerateRandomSequence(unsigned long uRandomSeqSize,
	unsigned char *pBuffer) const
{
	ATLASSERT(uRandomSeqSize <= 32); // Only up to 32-byte long random sequence is supported for now!
	if(uRandomSeqSize > 32) uRandomSeqSize = 32;

	CGetRandRomDlg dlg;
	if(dlg.DoModal() == IDCANCEL) return FALSE;

	memcpy(pBuffer, dlg.m_pFinalRandom, uRandomSeqSize);
	return TRUE;
}
CPasswordMgrUiHandler::~CPasswordMgrUiHandler(void)
{
	if(m_nClipboardCountdown >= 0)
	{
		m_nClipboardCountdown = -1; // Disable clipboard clear countdown

		ClearClipboardIfOwner();
	}

	if(m_ctrlSearch.IsWindow())
		m_ctrlSearch.DestroyWindow();
	if(m_wndListCtrl.IsWindow())
		m_wndListCtrl.DestroyWindow();
	if(m_PswCateTree.IsWindow())
		m_PswCateTree.DestroyWindow();
}

void CPasswordMgrUiHandler::Init()
{
	m_nClipboardCountdown = -1;
	m_dlg->SetTimer(APPWND_TIMER_ID, 1000, NULL);
	m_PswCateTree.m_ImageList = &(m_dlg->GetilIcons());
	m_PswCateTree.Create(
		m_dlg->GetViewHWND(), NULL, NULL, 
		WS_CLIPCHILDREN | WS_CHILD |WS_VSCROLL | LBS_HASSTRINGS , 
		0, IDC_PSW_TREEVIEW, NULL);
	
	m_PswCateTree.SetPswCallback(this);
	

	m_wndListCtrl.Create(m_dlg->GetViewHWND(),
		NULL,
		NULL,
		WS_VISIBLE | WS_CHILDWINDOW ,
		0,IDC_PSW_LISTVIEW);
	m_wndListCtrl.SetImageList( m_dlg->GetilIcons() );
	m_wndListCtrl.SetFocusSubItem( TRUE );
	
	m_wndListCtrl.AddColumn( BkString::Get(114), 100 );
	m_wndListCtrl.AddColumn( BkString::Get(115), 100 );
	m_wndListCtrl.AddColumn( BkString::Get(116), 100 );
	m_wndListCtrl.AddColumn( BkString::Get(117), 150 );
	m_wndListCtrl.AddColumn( BkString::Get(118), 150 );
	m_wndListCtrl.AddColumn( BkString::Get(119), 120 );
	m_wndListCtrl.AddColumn( BkString::Get(120), 120 );
	m_wndListCtrl.AddColumn( BkString::Get(121), 120 );
	m_wndListCtrl.AddColumn( BkString::Get(122), 120 );
	m_wndListCtrl.AddColumn( BkString::Get(123), 150 );
	
	/*CIni ini;
	ini.SetSection(SETTING_SECTION_PASSWORD);*/
	CString szTemp = thePrefs.m_PswSettings.Genp_Profile ;// ini.GetString(PWMKEY_GENPROFILEAUTO);
	if(szTemp.GetLength() > 0)
	{
		std::basic_string<TCHAR> strAutoProfile = szTemp;
		PwgStringToProfile(strAutoProfile, &m_pgsAutoProfile);
	}
	else PwgGetDefaultProfile(&m_pgsAutoProfile);
	m_nLockTimeDef = thePrefs.m_PswSettings.Idle_Second ;
	m_ctrlSearch.Create(m_dlg->GetViewHWND(), NULL, _T(""), WS_CHILD | WS_VISIBLE | WS_BORDER | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, IDC_PSW_EDIT_SEARCH);
}

void CPasswordMgrUiHandler::OnClickPassword(int nID)
{
	NotifyUserActivity();
	m_nClassID = nID;
	m_wndListCtrl.DeleteAllItems();
	PswPfList* pList = m_mgr.GetEntries();
	if(NULL == pList)
		return;
	POSITION Pos = pList->GetHeadPosition();
	while(NULL != Pos)
	{
		CPasswordProfile* pD = pList->GetNext(Pos);
		if(pD && (pD->m_nClassID == m_nClassID || m_nClassID == 0))
		{
			m_mgr.UnlockEntryPassword(pD);
			int idx = m_wndListCtrl.AddItem(pD->m_strTitle,pD->m_nIcon);
			m_wndListCtrl.SetItemText(idx,1,pD->m_strUserName );
			m_wndListCtrl.SetItemText(idx,2,L"**********" );
			
			m_mgr.LockEntryPassword(pD);
			m_wndListCtrl.SetItemText(idx,3,pD->m_strAddress );
			m_wndListCtrl.SetItemText(idx,4,pD->m_strRemark );
			SYSTEMTIME stDateTime;
			pD->m_tCreate.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 5, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,5,stDateTime );

			pD->m_tEdit.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 6, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,6,stDateTime );

			pD->m_tAccess.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 7, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,7,stDateTime );
			
			pD->m_tExpire.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 8, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,8,stDateTime );
			m_wndListCtrl.SetItemData(idx,pD);
			m_wndListCtrl.SetItemText(idx,9,pD->m_strAttachName );

		}
	}
}


void CPasswordMgrUiHandler::OnBtnGroupNew()
{
	CCategoryDlg cateDlg(L"PSW");
	cateDlg.m_pParentIcons = &(m_dlg->GetilIcons());
	UINT uId = cateDlg.DoModal();
	
	CString strCate = cateDlg.GetCategory();
	if(uId == IDOK)
	{
		
		HTREEITEM item = m_PswCateTree.GetSelectedItem();
		if(NULL == item)
		{
			CPkmpMsgBox2::ShowMultLine( BkString::Get(33), BkString::Get(1),  MB_OK|MB_ICONWARNING);
			return;
		}
		int nID = (int)m_PswCateTree.GetItemData(item);
		
		CCategoryManager cateMag ;
		Category cate;
		cate.m_strCate = strCate;
		cate.m_Parent = nID;
		cate.m_strClass =  L"PSW";
		cate.m_Icon = cateDlg.m_nSelIcon;
		cate.m_MasterId = m_nMasterID;
		if(cateMag.Add(&m_PswCateTree,&cate))
		{
			CPkmpMsgBox2::Show( BkString::Get(69), BkString::Get(1),  MB_OK|MB_ICONWARNING);
		}
	}
}
void CPasswordMgrUiHandler::OnBtnGroupSubNew()
{
	CCategoryDlg cateDlg(L"PSW");
	cateDlg.m_pParentIcons = &(m_dlg->GetilIcons());
	UINT uId = cateDlg.DoModal();
	if(uId == IDOK)
	{
		
		HTREEITEM item = m_PswCateTree.GetSelectedItem();
		HTREEITEM parent = m_PswCateTree.GetParentItem(item);
		if(NULL == parent)
		{
			CPkmpMsgBox2::ShowMultLine( BkString::Get(33), BkString::Get(1),  MB_OK|MB_ICONWARNING);
			return;
		}
		int nID = (int)m_PswCateTree.GetItemData(parent);
		CString strCate = cateDlg.GetCategory();
		CCategoryManager cateMag ;
		Category cate;
		cate.m_strCate = strCate;
		cate.m_Parent = nID;
		cate.m_Icon = cateDlg.m_nSelIcon;
		cate.m_MasterId = m_nMasterID;
		cate.m_strClass = L"PSW";
		if(cateMag.Add(&m_PswCateTree,&cate))
		{
			CPkmpMsgBox2::Show( BkString::Get(69), BkString::Get(1),  MB_OK|MB_ICONWARNING);
		}
	}
}
void CPasswordMgrUiHandler::OnBtnGroupRename()
{
	int classid = 0;
	HTREEITEM hItem= m_PswCateTree.GetSelectedItem();
	if(!hItem)
	{
		CPkmpMsgBox2::ShowMultLine( BkString::Get(33), BkString::Get(1),  MB_OK|MB_ICONWARNING);
		return;
	}
	classid = (int)m_PswCateTree.GetItemData(hItem);
	//m_wndCateView.GetItemData(hItem);
	CCategoryDlg cateDlg(L"PSW-RENAME");
	cateDlg.m_pParentIcons = &(m_dlg->GetilIcons());
	UINT uId = cateDlg.DoModal();
	if(uId == IDOK)
	{
		CString strCate = cateDlg.GetCategory();
		CCategoryManager cateMag ;
		cateMag.Rename(&m_PswCateTree,classid,strCate);

	}
}
void CPasswordMgrUiHandler::OnBtnGroupDelete()
{
	int classid = 0;
	HTREEITEM hItem= m_PswCateTree.GetSelectedItem();
	if(!hItem)
	{
		CPkmpMsgBox2::ShowMultLine( BkString::Get(33), BkString::Get(1),  MB_OK|MB_ICONWARNING);
		return;
	}
	classid = (int)m_PswCateTree.GetItemData(hItem);
	if(classid == 0)
	{
		CPkmpMsgBox2::ShowMultLine( BkString::Get(35), BkString::Get(1),  MB_OK|MB_ICONWARNING);
		return;
	}
	if(CPkmpMsgBox2::Show( BkString::Get(70), BkString::Get(1),  MB_YESNO|MB_ICONWARNING) != IDYES)
		return;
	CCategoryManager cateMag ;
	if(cateMag.Remove(&m_PswCateTree,classid))
		CPkmpMsgBox2::Show( BkString::Get(29), BkString::Get(1),  MB_OK);
}
void CPasswordMgrUiHandler::OnBtnGroupExpands()
{
	HTREEITEM hParent = m_PswCateTree.GetRootItem();
	m_PswCateTree.Expands(hParent);
}
	
void CPasswordMgrUiHandler::OnBtnGroupCollapse()
{
	HTREEITEM hParent = m_PswCateTree.GetRootItem();

	m_PswCateTree.Collapses(hParent);
}

void CPasswordMgrUiHandler::OnBtnAccountNew()
{
	NotifyUserActivity();
	if(FALSE == m_bFileOpen)
	{
		CPkmpMsgBox2::Show(BkString::Get(136),BkString::Get(88));
		return;
	}
	if(m_nClassID == 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(113),BkString::Get(88));
		return;
	}
	CAddAccountDlg addDlg(m_nClassID);
	addDlg.m_pMgr = &m_mgr;
	addDlg.m_pParentIcons = &(m_dlg->GetilIcons());
	addDlg.m_nGroupId = m_nClassID;
	addDlg.m_bEditMode = FALSE;
	addDlg.m_nMasterID = m_nMasterID;
	m_mgr.GetNeverExpireTime(addDlg.m_tExpire);
	if (addDlg.DoModal() == IDOK)
	{
		m_bModified = TRUE;
		OnClickPassword(m_nClassID);
	}
}
void CPasswordMgrUiHandler::OnBtnAccountEdit()
{
	NotifyUserActivity();
	int nItem = m_wndListCtrl.GetFocusItem();
	if(nItem < 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return;
	}
	CPasswordProfile* pP = NULL;
	m_wndListCtrl.GetItemData(nItem,pP);
	if(NULL == pP)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return;
	}
	CAddAccountDlg addDlg(m_nClassID);
	addDlg.m_pMgr = &m_mgr;
	addDlg.m_pParentIcons = &(m_dlg->GetilIcons());
	addDlg.m_nGroupId = m_nClassID;
	addDlg.m_bEditMode = TRUE;
	addDlg.m_nMasterID = m_nMasterID;
	addDlg.m_pOriginalEntry = pP;
	m_mgr.GetNeverExpireTime(addDlg.m_tExpire);
	
	if(addDlg.DoModal() == IDOK)
	{
		m_bModified = TRUE;
		OnClickPassword(m_nClassID);
	}
}
void CPasswordMgrUiHandler::OnBtnAccountDelete()
{
	NotifyUserActivity();
	int nItem = m_wndListCtrl.GetFocusItem();
	if(nItem < 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return;
	}
	CPasswordProfile* pP = NULL;
	m_wndListCtrl.GetItemData(nItem,pP);
	if(NULL == pP)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return;
	}
	if(m_mgr.DeleteEntry(pP))
	{
		m_wndListCtrl.DeleteItem(nItem);
	}
	//m_mgr.
}
void CPasswordMgrUiHandler::OnBtnAccountCopyUser()
{
	NotifyUserActivity();
	int nItem = m_wndListCtrl.GetFocusItem();
	if(nItem < 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return ;
	}
	CPasswordProfile* pP = NULL;
	m_wndListCtrl.GetItemData(nItem,pP);
	if(NULL == pP)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return ;
	}
	m_mgr.UnlockEntryPassword(pP);
	CopyStringToClipboard(pP->m_strUserName ,pP,&m_mgr);
	m_mgr.LockEntryPassword(pP);
}
void CPasswordMgrUiHandler::OnBtnAccountCopyPsw()
{
	NotifyUserActivity();
	int nItem = m_wndListCtrl.GetFocusItem();
	if(nItem < 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return ;
	}
	CPasswordProfile* pP = NULL;
	m_wndListCtrl.GetItemData(nItem,pP);
	if(NULL == pP)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return ;
	}
	m_mgr.UnlockEntryPassword(pP);
	CopyStringToClipboard(pP->m_strPassword ,pP,&m_mgr);
	m_mgr.LockEntryPassword(pP);
	m_nClipboardCountdown = thePrefs.m_PswSettings.Wait_Second;
}
void CPasswordMgrUiHandler::OnBtnAccountLock()
{
	m_bDisplayDialog = TRUE;
	
	if((m_bFileOpen == TRUE) && (m_bModified == TRUE))
	{
		int nRes;

		nRes = CPkmpMsgBox2::Show(BkString::Get(135),BkString::Get(88),MB_YESNOCANCEL);

		if(nRes == IDCANCEL) { m_bDisplayDialog = FALSE; return; }
		else if(nRes == IDYES)
		{
			OnBtnPswDbSave();
		}
		else m_bModified = FALSE; // nRes == IDNO
	}


	m_wndListCtrl.DeleteAllItems();
	m_PswCateTree.DeleteAllItems();
	
	m_mgr.NewDatabase();
	m_mgr.ClearMasterKey(TRUE, TRUE);

	m_bLocked = TRUE;
	m_bFileOpen = FALSE;
	// m_bFileReadOnly = FALSE;
	m_bModified = FALSE;

	//m_cList.EnableWindow(FALSE);
//	m_cGroups.EnableWindow(FALSE);

	m_bDisplayDialog = FALSE;
}
void CPasswordMgrUiHandler::OnBtnAccountSearch()
{
	m_wndListCtrl.DeleteAllItems();
	PswPfList* pList = m_mgr.GetEntries();
	if(NULL == pList)
		return;
	CString strFind ;
	m_ctrlSearch.GetWindowTextEx(strFind);
	POSITION Pos = pList->GetHeadPosition();

	while(NULL != Pos)
	{
		CPasswordProfile* pD = pList->GetNext(Pos);
		BOOL bFind = FALSE;
		if(pD->m_strTitle.Find(strFind) >= 0)
		{
			bFind = TRUE;
		}
		if(bFind || pD->m_strAddress.Find(strFind) >= 0)
		{
			bFind = TRUE;
		}
		m_mgr.UnlockEntryPassword(pD);
		if(bFind || pD->m_strPassword.Find(strFind) >= 0)
		{
			bFind = TRUE;
		}
		if(bFind || pD->m_strPassword.Find(strFind) >= 0)
		{
			bFind = TRUE;
		}
		m_mgr.LockEntryPassword(pD);
		if(bFind || pD->m_strAttachName.Find(strFind) >= 0)
		{
			bFind = TRUE;
		}
		if(bFind || pD->m_strRemark.Find(strFind) >= 0)
		{
			bFind = TRUE;
		}
		if(bFind == TRUE)
		{
			m_mgr.UnlockEntryPassword(pD);
			int idx = m_wndListCtrl.AddItem(pD->m_strTitle,pD->m_nIcon);
			m_wndListCtrl.SetItemText(idx,1,pD->m_strUserName );
			m_wndListCtrl.SetItemText(idx,2,L"**********" );
			
			m_mgr.LockEntryPassword(pD);
			m_wndListCtrl.SetItemText(idx,3,pD->m_strAddress );
			m_wndListCtrl.SetItemText(idx,4,pD->m_strRemark );
			SYSTEMTIME stDateTime;
			pD->m_tCreate.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 5, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,5,stDateTime );

			pD->m_tEdit.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 6, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,6,stDateTime );

			pD->m_tAccess.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 7, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,7,stDateTime );
			
			pD->m_tExpire.GetAsSystemTime( stDateTime );
			m_wndListCtrl.SetItemFormat(idx, 8, ITEM_FORMAT_DATETIME, ITEM_FLAGS_DATETIME_NONE );
			m_wndListCtrl.SetItemDate(idx,8,stDateTime );
			m_wndListCtrl.SetItemData(idx,pD);
			m_wndListCtrl.SetItemText(idx,9,pD->m_strAttachName );
		}
	}
}
void CPasswordMgrUiHandler::OnBtnPswDbNew()
{
	NotifyUserActivity();
	//if(m_bFileOpen == TRUE) OnFileClose();
	if(m_bFileOpen == TRUE) return;

	

	m_mgr.NewDatabase();
	if(_ChangeMasterKey(NULL, TRUE) == FALSE) return;
	CPasswordManager pswMg;
	m_nMasterID = pswMg.GetNextID();
	m_PswCateTree.Load(m_nMasterID);
	m_bFileOpen = TRUE;
	m_bLocked = FALSE;
	/*m_cList.EnableWindow(TRUE);
	m_cGroups.EnableWindow(TRUE);*/
	m_bModified = TRUE;

	//m_mgr.FixGroupTree();
	/*UpdateGroupList();
	UpdatePasswordList();
	_UpdateToolBar();
	_SetDefaultFocus();*/
}
BOOL CPasswordMgrUiHandler::_ChangeMasterKey(CPwManager *pDbMgr, BOOL bCreateNew)
{
	CPasswordDlg dlg;
	dlg.m_ilIcons = &(m_dlg->GetilIcons());
	int nConfirmAttempts;
	BOOL bSuccess;
	CPwManager *pMgr;

	if(pDbMgr == NULL) pMgr = &m_mgr;
	else pMgr = pDbMgr;

	m_bDisplayDialog = TRUE;

	dlg.m_bKeyMethod = PWM_KEYMETHOD_OR;
	dlg.m_bConfirm = FALSE;
	dlg.m_bLoadMode = FALSE;
	dlg.m_bChanging = ((bCreateNew == FALSE) ? TRUE : FALSE);

	if(dlg.DoModal() == IDCANCEL) { m_bDisplayDialog = FALSE; return FALSE; }
	m_strLastName = dlg.GetName();
	if(bCreateNew)
	{
		CPasswordManager pMM;
		if(pMM.IsExist(m_strLastName))
		{
			CPkmpMsgBox2::Show(BkString::Get(124),
						BkString::Get(88), MB_OK | MB_ICONINFORMATION);
			return FALSE;
		}
	}
	if((dlg.m_bKeyFile == FALSE) || (dlg.m_bKeyMethod == PWM_KEYMETHOD_AND))
	{
		bSuccess = FALSE;

		for(nConfirmAttempts = 0; nConfirmAttempts < 3; ++nConfirmAttempts)
		{
			CPasswordDlg *pDlg2 = new CPasswordDlg();
			pDlg2->m_ilIcons = &(m_dlg->GetilIcons());
			ATLASSERT(pDlg2 != NULL); if(pDlg2 == NULL) continue;

			pDlg2->m_bKeyMethod = PWM_KEYMETHOD_OR;
			pDlg2->m_bConfirm = TRUE;
			pDlg2->m_bLoadMode = FALSE;
			pDlg2->m_bChanging = ((bCreateNew == TRUE) ? FALSE : TRUE);
			//::SetWindowPos(pDlg2->m_hWnd,HWND_TOP,0,0,400,250,SWP_NOMOVE);
			if(pDlg2->DoModal() == IDCANCEL)
			{
				ATLASSERT((pDlg2->m_lpKey == NULL) && (pDlg2->m_lpKey2 == NULL));
				SAFE_DELETE(pDlg2);
				dlg.FreePasswords();
				m_bDisplayDialog = FALSE;
				return FALSE;
			}

			if(dlg.m_bKeyMethod == PWM_KEYMETHOD_OR)
			{
				if((_tcscmp(pDlg2->m_lpKey, dlg.m_lpKey) != 0) || (pDlg2->m_bKeyFile == TRUE))
				{
					pDlg2->FreePasswords();
					SAFE_DELETE(pDlg2);
					CPkmpMsgBox2::Show(BkString::Get(1011),BkString::Get(88),MB_ICONWARNING | MB_OK);

					continue;
				}
			}
			else // dlg.m_nKeyMethod == PWM_KEYMETHOD_AND
			{
				if((_tcscmp(pDlg2->m_lpKey, dlg.m_lpKey2) != 0) || (pDlg2->m_bKeyFile == TRUE))
				{
					pDlg2->FreePasswords();
					SAFE_DELETE(pDlg2);
					CPkmpMsgBox2::Show(BkString::Get(1011),BkString::Get(88),MB_ICONWARNING | MB_OK);
					continue;
				}
			}

			pDlg2->FreePasswords();
			SAFE_DELETE(pDlg2);
			bSuccess = TRUE;
			break;
		}

		if(bSuccess == FALSE) { dlg.FreePasswords(); m_bDisplayDialog = FALSE; return FALSE; }
	}
	pMgr->m_dbLastHeader->m_PswAndKey  = 0;
	CPwSafeAppRI ri;
	int nErrCode;

	if(dlg.m_bKeyMethod == PWM_KEYMETHOD_OR)
		nErrCode = pMgr->SetMasterKey(dlg.m_lpKey, dlg.m_bKeyFile, NULL, &ri, FALSE,
			dlg.m_strSelectedKeyProv);
	else
	{
		ATLASSERT(dlg.m_bKeyFile == TRUE);
		nErrCode = pMgr->SetMasterKey(dlg.m_lpKey, dlg.m_bKeyFile, dlg.m_lpKey2, &ri,
			FALSE, dlg.m_strSelectedKeyProv);
	}
	

	if(pDbMgr == NULL) m_bModified = TRUE;

	dlg.FreePasswords();
	pMgr->m_dbLastHeader->m_nID = m_nMasterID;
	pMgr->m_dbLastHeader->m_Name = m_strLastName;
	pMgr->m_dbLastHeader->m_Type = L"PSW";
	
	/*if(bCreateNew == FALSE)
	{
		CString str = TRL("The composite master key has been changed!");
		str += _T("\r\n\r\n");
		str += TRL("Save the database now in order to get the new key applied.");
		MessageBox(str, TRL("Success"), MB_ICONINFORMATION | MB_OK);
	}*/

	m_bDisplayDialog = FALSE;
	return TRUE;
}

void CPasswordMgrUiHandler::OnBtnPswDbOpen()
{
	//CGetRandRomDlg dlg;
	//if(dlg.DoModal() == IDCANCEL) return;
	m_bDisplayDialog = TRUE;
	NotifyUserActivity();

	_OpenDatabase(NULL, NULL, NULL, NULL, FALSE);
	m_bDisplayDialog = FALSE;
	m_bFileOpen = TRUE;
	m_bLocked = FALSE;


}
void CPasswordMgrUiHandler::OnBtnPswDbSave()
{
	NotifyUserActivity();
	if(FALSE == m_bFileOpen && FALSE == m_bModified )
		return;
	int res = m_mgr.SaveDatabase(m_strLastName);
	m_bModified = FALSE;
	CPkmpMsgBox2::Show(CPwUtil::FormatError(res,PWFF_NO_INTRO |	PWFF_INVKEY_WITH_CODE),BkString::Get(88));
}
void CPasswordMgrUiHandler::_OpenDatabase(CPwManager *pDbMgr, const TCHAR *pszName,
										  const TCHAR *pszPassword, const TCHAR *pszKeyFile, BOOL bOpenLocked)
{
	NotifyUserActivity();
	INT_PTR nRet = IDCANCEL;
	int nErr;
	const TCHAR *pSuffix = _T("");
	CPasswordDlg *pDlgPass = NULL;
	CPwManager *pMgr;


	if(pDbMgr == NULL) 
		pMgr = &m_mgr;
	if((bOpenLocked == TRUE) && (pDbMgr == NULL))
	{
		m_strLastName = pszName;
		//m_strFileAbsolute = GetShortestAbsolutePath(m_strFile);

		m_bLocked = TRUE;
		/*CString strExtended = TRL("&Unlock Workspace");
		strExtended += _T("\t");
		strExtended += _GetCmdAccelExt(_T("&Lock Workspace"));
		m_menu.SetMenuText(ID_FILE_LOCK, strExtended, MF_BYCOMMAND);
		SetStatusTextEx(CString(TRL("Workspace locked")) + _T("."));
		m_btnTbLock.SetTooltipText(RemoveAcceleratorTipEx(TRL("&Unlock Workspace")));*/
	}
	else
	{
		int nAllowedAttempts;
		if((pszPassword != NULL) || (pszKeyFile != NULL)) nAllowedAttempts = 1;
		else nAllowedAttempts = 3;

		for(int nOpenAttempts = 0; nOpenAttempts < nAllowedAttempts; ++nOpenAttempts)
		{
			ATLASSERT(pDlgPass == NULL); if(pDlgPass != NULL) { pDlgPass->FreePasswords(); delete pDlgPass; }
			pDlgPass = new CPasswordDlg();
			ATLASSERT(pDlgPass != NULL); if(pDlgPass == NULL) continue;

			pDlgPass->m_ilIcons = &(m_dlg->GetilIcons());
			pDlgPass->m_bConfirm = FALSE;
			pDlgPass->m_bLoadMode = TRUE;
			pDlgPass->m_bChanging = FALSE;
			//	pDlgPass->m_hWindowIcon = m_hIcon;
			//	pDlgPass->m_lpPreSelectPath = lpPreSelectPath;
			//pDlgPass->SetName(m_strLastName);

			

			if((pszPassword == NULL) && (pszKeyFile == NULL))
			{
				m_bDisplayDialog = TRUE;

				if(pDlgPass->DoModal() == IDCANCEL)
				{
					delete pDlgPass; pDlgPass = NULL;
					m_bDisplayDialog = FALSE;


					return;
				}
				m_strLastName = pDlgPass->GetName ();
				m_bDisplayDialog = FALSE;
				/*--g_uMasterKeyDlgs;
				CPwSafeDlg::SetLastMasterKeyDlg(NULL);*/
			}
			else
			{
				if(pszKeyFile != NULL)
				{
					pDlgPass->m_bKeyFile = TRUE;
					pDlgPass->m_lpKey = _TcsSafeDupAlloc(pszKeyFile);

					if(pszPassword != NULL)
					{
						pDlgPass->m_lpKey2 = _TcsSafeDupAlloc(pszPassword);
						pDlgPass->m_bKeyMethod = PWM_KEYMETHOD_AND;
					}
					else pDlgPass->m_bKeyMethod = PWM_KEYMETHOD_OR;
				}
				else // pszKeyFile == NULL
				{
					pDlgPass->m_bKeyFile = FALSE;
					pDlgPass->m_lpKey = _TcsSafeDupAlloc(pszPassword);
					pDlgPass->m_bKeyMethod = PWM_KEYMETHOD_OR;
				}
			}
			m_nMasterID = pDlgPass->m_MasterId ;
			CString strKeyFilePath;
			if((pDlgPass->m_bKeyFile != FALSE) && (pDlgPass->m_lpKey != NULL))
				strKeyFilePath = pDlgPass->m_lpKey;

			if(pDlgPass->m_bKeyMethod == PWM_KEYMETHOD_OR)
				nErr = pMgr->SetMasterKey(pDlgPass->m_lpKey, pDlgPass->m_bKeyFile,
				NULL, NULL, FALSE, pDlgPass->m_strSelectedKeyProv);
			else
				nErr = pMgr->SetMasterKey(pDlgPass->m_lpKey, pDlgPass->m_bKeyFile,
				pDlgPass->m_lpKey2, NULL, FALSE, pDlgPass->m_strSelectedKeyProv);

			pDlgPass->FreePasswords(); delete pDlgPass; pDlgPass = NULL;

			if(nErr != PWE_SUCCESS)
			{
				CPkmpMsgBox2::Show(BkString::Get(1010) , BkString::Get(1),  MB_OK|MB_ICONWARNING);
				//CNewDialogsEx::ShowError(this->m_hWnd, nErr, 0);
				continue;
			}

			//	CTaskbarListEx::SetProgressState(this->m_hWnd, TBPF_INDETERMINATE);

			nErr = pMgr->OpenDatabase(m_strLastName);

			//		CTaskbarListEx::SetProgressState(this->m_hWnd, TBPF_NOPROGRESS);
			
			
			if(nErr != PWE_SUCCESS)
			{
				CPkmpMsgBox2::Show( BkString::Get(1010), BkString::Get(1),  MB_OK|MB_ICONWARNING);

				if(nErr == PWE_UNSUPPORTED_KDBX) nOpenAttempts = nAllowedAttempts;
			}
			else
			{
				m_nMasterID = pMgr->m_dbLastHeader->m_nID;
				m_PswCateTree.Load(m_nMasterID);
				OnClickPassword(0);
				OnBtnGroupExpands();
				return;
			}
		}
	}

}



LRESULT CPasswordMgrUiHandler:: OnListViewLButtonUp(LPNMHDR pnmh)
{
	NotifyUserActivity();
	POINT point = { 0 };
    ::GetCursorPos(&point);
	::ScreenToClient(m_wndListCtrl.m_hWnd,&point);
	::ClientToScreen(m_wndListCtrl.m_hWnd,&point);
	TPMPARAMS tpmp = { sizeof(tpmp) };
	//rcButton.bottom -= 1;

	RECT rcButton;
	rcButton.left = point.x ;
	rcButton.right = rcButton.left - 30;
	rcButton.top = point.y ;
	rcButton.bottom = rcButton.top - 20;
	//::GetWindowRect(m_wndListCtrl.m_hWnd,& rcButton);
	tpmp.rcExclude = rcButton;
	CMenu menu;
	menu.LoadMenu(IDR_PWLIST_MENU);
	CMenuHandle submenu = menu.GetSubMenu(0);
	TrackPopupMenuEx(submenu, TPM_LEFTBUTTON, point.x, point.y,m_dlg->GetViewHWND(), &tpmp);
	return 0L;
}

LRESULT CPasswordMgrUiHandler::OnListCopyUser(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	OnBtnAccountCopyUser();
	return 0L;

}
LRESULT CPasswordMgrUiHandler::OnListCopyPsw(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	OnBtnAccountCopyPsw();
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnListVisitUrl(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{	
	NotifyUserActivity();
	int nItem = m_wndListCtrl.GetFocusItem();
	if(nItem < 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return 0L;
	}
	CPasswordProfile* pP = NULL;
	m_wndListCtrl.GetItemData(nItem,pP);
	if(NULL == pP)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return 0L;
	}
	ParseAndOpenURLWithEntryInfo(pP->m_strAddress, pP);
	return 0L;
}
void CPasswordMgrUiHandler::ParseAndOpenURLWithEntryInfo(LPCTSTR lpURL, CPasswordProfile *pEntry)
{
	if((pEntry != NULL) && (lpURL != NULL))
	{
		CString strURL = lpURL;

		if(strURL.GetLength() != 0)
		{
			CString strOverride;
			strOverride = ExtractParameterFromString(pEntry->m_strAddress, _T("url-override:"), 0);
			if(strOverride.GetLength() != 0)
				strURL = strOverride;

			const bool bCmdQuotes = WU_IsCommandLineURL(strURL);

			strURL = SprCompile(strURL, false, pEntry, &m_mgr, false, bCmdQuotes);

			strURL = strURL.TrimLeft(_T(" \t\r\n"));

			if(WU_IsCommandLineURL(strURL) == false) FixURL(&strURL);

			if(strURL.GetLength() != 0)
			{
				/*if(m_bUsePuttyForURLs == TRUE)
				{
					CString strUser = SprCompile(pEntry->pszUserName, false, pEntry,
						&m_mgr, false, true);
					if(OpenUrlUsingPutty(strURL, strUser) == FALSE)
						OpenUrlEx(strURL, this->m_hWnd);
				}
				else*/ 
				OpenUrlEx(strURL, m_dlg->GetViewHWND());
			}
		}
	}
}
LRESULT CPasswordMgrUiHandler::OnListSaveAttach(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	int nItem = m_wndListCtrl.GetFocusItem();
	if(nItem < 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return 0L;
	}
	CPasswordProfile* pP = NULL;
	m_wndListCtrl.GetItemData(nItem,pP);
	if(NULL == pP)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return 0L;
	}
	if(pP->m_strAttachName.GetLength() == 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(132),
			BkString::Get(88), MB_ICONINFORMATION | MB_OK);
		return 0L;
	}
	
	CString strSample = pP->m_strAttachName;

	CString strFilter = BkString::Get(1009);
	strFilter += _T(" (*.*)|*.*||");

	DWORD dwFlags = OFN_LONGNAMES | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
	dwFlags |= OFN_EXTENSIONDIFFERENT;
	// OFN_EXPLORER = 0x00080000, OFN_ENABLESIZING = 0x00800000
	dwFlags |= 0x00080000 | 0x00800000 | OFN_NOREADONLYRETURN;
	ConvertToWtlFileDialogFilter((LPWSTR)(LPCTSTR)strFilter);
	CFileDialog dlg(FALSE, NULL, strSample, dwFlags, strFilter, m_dlg->GetViewHWND());
	if(dlg.DoModal() == IDOK)
		CPwUtil::SaveBinaryData(pP, dlg.m_szFileName);
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnListAutoType(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	int nItem = m_wndListCtrl.GetFocusItem();
	if(nItem < 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return 0L;
	}
	CPasswordProfile* pP = NULL;
	m_wndListCtrl.GetItemData(nItem,pP);
	if(NULL == pP)
	{
		CPkmpMsgBox2::Show(BkString::Get(134),BkString::Get(88));
		return 0L;
	}
	_AutoType(pP, TRUE, 0, NULL);
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnListAccountAdd(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	OnBtnAccountNew();
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnListAccountEdit(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	OnBtnAccountEdit();
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnListAccountDelete(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	OnBtnAccountDelete();
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnListSelectAll(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	//m_wndListCtrl.se
	return 0L;
}
void CPasswordMgrUiHandler::_AutoType(CPasswordProfile *pEntry, BOOL bLoseFocus, DWORD dwAutoTypeSeq,
	LPCTSTR lpTargetWindowName)
{
	BOOL bRefreshView = FALSE;
	NotifyUserActivity();
	if(pEntry == NULL) return;


	const BOOL bNoBlockInput = AU_IsWin9xSystem();
	if(bNoBlockInput == FALSE) ::BlockInput(TRUE);

	CString strLookup;
	if(dwAutoTypeSeq == 0) strLookup = _T("auto-type:");
	else strLookup.Format(_T("%s%d%s"), _T("auto-type-"), dwAutoTypeSeq, _T(":"));

	CString str = ExtractParameterFromString(pEntry->m_strAddress, strLookup, 0);
	if(str.GetLength() == 0)
	{
	//	//if(CPwUtil::IsTANEntry(pEntry) == TRUE) // Is it a TAN entry?
	//	//{
	//	//	str = _T("{PASSWORD}");

	//	//	
	//	//	m_bModified = TRUE;
	//	//	bRefreshView = TRUE;
	//	//}
	//	//else 
		str = m_strDefaultAutoTypeSequence;
	}

	str = SprCompile(str, true, pEntry, &m_mgr, true, false);

	if( (lpTargetWindowName != NULL) &&
		((_tcsstr(lpTargetWindowName, _T("Windows Internet Explorer")) != NULL) ||
		(_tcsstr(lpTargetWindowName, _T("Maxthon")) != NULL)))
	{
		str = CString(_T("{DELAY 50}1{DELAY 50}{BACKSPACE}")) + str;
	}

	if(bLoseFocus == TRUE)
	{
		if(m_nAutoTypeMethod == ATM_DROPBACK)
		{
			SafeActivateNextWindow(m_dlg->m_hWnd);
		}
		else //m_nAutoTypeMethod == ATM_MINIMIZE
		{
			const BOOL bPrevIgnoreSizeEvent = m_bIgnoreSizeEvent;
			m_bIgnoreSizeEvent = TRUE;

			HWND hMe = ::GetForegroundWindow();

			if(m_bMinimized == FALSE)
			{
				if(m_bMinimizeToTray == TRUE)
					SafeActivateNextWindow(m_dlg->m_hWnd);

				::ShowWindow(m_dlg->m_hWnd,SW_MINIMIZE);
			}
			else SafeActivateNextWindow(hMe);

			const DWORD dwStartTime = timeGetTime();
			while(1)
			{
				if(::GetForegroundWindow() != hMe) break;

				if((timeGetTime() - dwStartTime) > 1000) break;
				Sleep(50);
			}

			m_bIgnoreSizeEvent = bPrevIgnoreSizeEvent;
		}
	}

	Sleep(50);

	CSendKeysEx sk;
	BOOL bToggleCapsLock = FALSE;
	sk.SetDelay(10);

	// sk.SendKeys(_T("(^@+%)"), false); // Release all modifier keys
	sk.SendKeyUp(VK_LSHIFT); sk.SendKeyUp(VK_RSHIFT); sk.SendKeyUp(VK_SHIFT);
	sk.SendKeyUp(VK_LCONTROL); sk.SendKeyUp(VK_RCONTROL); sk.SendKeyUp(VK_CONTROL);
	sk.SendKeyUp(VK_LMENU); sk.SendKeyUp(VK_RMENU); sk.SendKeyUp(VK_MENU);
	sk.SendKeyUp(VK_LWIN); sk.SendKeyUp(VK_RWIN);

	if((GetKeyState(VK_CAPITAL) & 1) > 0)
		{ bToggleCapsLock = TRUE; sk.SendKeys(_T("({CAPSLOCK})"), true); }

	MSG msgClearWait;
	while(::PeekMessage(&msgClearWait, 0, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE))
	{
		::TranslateMessage(&msgClearWait);
		::DispatchMessage(&msgClearWait);
	}

	sk.SendKeys(str, true);

	if(bToggleCapsLock == TRUE) sk.SendKeys(_T("({CAPSLOCK})"), true);

	sk.Release();

	if(bNoBlockInput == FALSE) ::BlockInput(FALSE);

	/*if((bLoseFocus == TRUE) && (m_bAlwaysOnTop == TRUE))
		SetWindowPos(&CWnd::wndTopMost, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);*/

	//ATLASSERT(m_bLocked == FALSE);
	if((pEntry != NULL) && (m_bLocked == FALSE)) // Update last-access time
	{
		
		pEntry->m_tAccess = CTime::GetCurrentTime();

		m_bModified = TRUE;
	}
	EraseCString(&str);
}
void CPasswordMgrUiHandler::OnSearchKeyDown(UINT uNotifyCode, int nID, CWindow wndCtl)
{
	TCHAR key = (TCHAR)uNotifyCode;
	if( key == VK_RETURN)
	{
		OnBtnAccountSearch();
	}

}

LRESULT CPasswordMgrUiHandler::OnKeyDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	NotifyUserActivity();
	//UINT code == HIWORD(wParam);
	if(uMsg == IDC_PSW_EDIT_SEARCH)
	{
		if(wParam == VK_RETURN)
			OnBtnAccountSearch();
	}
	return 0;
}
void CPasswordMgrUiHandler::OnKeyDownReturn(MSG* pMsg)
{
	NotifyUserActivity();
	if(pMsg->wParam == VK_RETURN && m_ctrlSearch.m_ctrlEdit.m_hWnd == pMsg->hwnd)
	{
		OnBtnAccountSearch();
	}
}

void CPasswordMgrUiHandler::OnBtnPswDbExport()
{
	NotifyUserActivity();
	RECT rcButton;
	m_dlg->GetItemRect(IDC_PSW_BTN_EXPORT,rcButton);
	POINT point;
	point.x = rcButton.left;
	point.y = rcButton.bottom ;
	::ClientToScreen(m_dlg->GetViewHWND(),&point);
	TPMPARAMS tpmp = { sizeof(tpmp) };
	//rcButton.bottom -= 1;
	tpmp.rcExclude = rcButton;
	CMenu menu;
	menu.LoadMenu(IDR_PSW_EXPORT);
	CMenuHandle submenu = menu.GetSubMenu(0);
	//EnableItem(IDC_ACCOUNT_BTN_TOOLS,FALSE);
	TrackPopupMenuEx(submenu, TPM_LEFTBUTTON, point.x, point.y, m_dlg->GetViewHWND(), &tpmp);
	//EnableItem(IDC_ACCOUNT_BTN_EXPIRE,TRUE);
}
void CPasswordMgrUiHandler::OnBtnPswDbImport()
{
	NotifyUserActivity();
	RECT rcButton;
	m_dlg->GetItemRect(IDC_PSW_BTN_IMPORT,rcButton);
	POINT point;
	point.x = rcButton.left;
	point.y = rcButton.bottom ;
	::ClientToScreen(m_dlg->GetViewHWND(),&point);
	TPMPARAMS tpmp = { sizeof(tpmp) };
	//rcButton.bottom -= 1;
	tpmp.rcExclude = rcButton;
	CMenu menu;
	menu.LoadMenu(IDR_PSW_IMPORT);
	CMenuHandle submenu = menu.GetSubMenu(0);
	//EnableItem(IDC_ACCOUNT_BTN_TOOLS,FALSE);
	TrackPopupMenuEx(submenu, TPM_LEFTBUTTON, point.x, point.y, m_dlg->GetViewHWND(), &tpmp);
}
CString CPasswordMgrUiHandler::GetExportFile(int nFormat, LPCTSTR lpBaseFileName, BOOL bFixFileName)
{
	if(m_bFileOpen == FALSE) return CString("");

	m_bDisplayDialog = TRUE;

	LPCTSTR lp = _T("exp");
	if(nFormat == PWEXP_TXT) lp = _T("txt");
	else if(nFormat == PWEXP_HTML) lp = _T("html");
	else if(nFormat == PWEXP_XML) lp = _T("xml");
	else if(nFormat == PWEXP_CSV) lp = _T("csv");
	else if(nFormat == PWEXP_KEEPASS) lp = _T("kdb");
	else { ATLASSERT(FALSE); }

	CString strSample;
	if(lpBaseFileName == NULL) strSample = _T("Export");
	else
	{
		strSample = lpBaseFileName;

		if(bFixFileName == TRUE)
		{
			strSample.Replace(_T('*'), _T('-')); strSample.Replace(_T('?'), _T('-'));
			strSample.Replace(_T(','), _T('-')); strSample.Replace(_T(';'), _T('-'));
			strSample.Replace(_T(':'), _T('-')); strSample.Replace(_T('|'), _T('-'));
			strSample.Replace(_T('<'), _T('-')); strSample.Replace(_T('>'), _T('-'));
			strSample.Replace(_T('/'), _T('-')); strSample.Replace(_T('\"'), _T('-'));
			strSample.Replace(_T('\\'), _T('-'));
		}
	}

	strSample += _T(".");
	strSample += lp;

	CString strFilter = BkString::Get(1009);
	strFilter += _T(" (*.*)|*.*||");

	const DWORD dwFlags = (OFN_LONGNAMES | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT |
		OFN_EXTENSIONDIFFERENT | OFN_EXPLORER | OFN_ENABLESIZING | OFN_NOREADONLYRETURN);
	ConvertToWtlFileDialogFilter((LPWSTR)(LPCTSTR)strFilter);
	CFileDialog dlg(FALSE, lp, strSample, dwFlags, strFilter, m_dlg->GetViewHWND());
	if(dlg.DoModal() == IDOK) { m_bDisplayDialog = FALSE; return dlg.m_szFileName; }

	strSample.Empty();
	m_bDisplayDialog = FALSE;
	return strSample;
}

BOOL CPasswordMgrUiHandler::GetExportOptions(PWEXPORT_OPTIONS *pOptions,
	CPwExport *pPwExport, BOOL bPrinting)
{


	ATLASSERT(pOptions != NULL); if(pOptions == NULL) return FALSE;
	ATLASSERT(pPwExport != NULL); if(pPwExport == NULL) return FALSE;

	m_bDisplayDialog = TRUE;

	*pOptions = pPwExport->m_aDefaults[pPwExport->m_nFormat];

	//CCheckOptionsDlg dlg;
	//CHKOPT_PARAM pa[LCL_CHKOPT_PARAM_COUNT];

	//ZeroMemory(pa, sizeof(CHKOPT_PARAM) * LCL_CHKOPT_PARAM_COUNT);

	/*DWORD n = DWORD_MAX;

	pa[++n].lpString = TRL("Options");
	pa[n].nIcon = 9;

	if(bPrinting == FALSE)
	{
		pa[++n].lpString = TRL("Encode/replace newline characters by '\\n'");
		pa[n].pbValue = &pOptions->bEncodeNewlines;
	}

	if(bPrinting == TRUE)
		pa[++n].lpString = TRL("Print backup entries (entries in the 'Backup' group)");
	else
		pa[++n].lpString = TRL("Export backup entries (entries in the 'Backup' group)");
	pa[n].pbValue = &pOptions->bExportBackups;

	pa[++n].lpString = _T("");
	pa[n].nIcon = 0;

	if(bPrinting == TRUE) pa[++n].lpString = TRL("Fields to print");
	else pa[++n].lpString = TRL("Fields to export");
	pa[n].nIcon = 8;

	pa[++n].lpString = TRL("Password Groups");
	pa[n].pbValue = &pOptions->bGroup;
	pa[++n].lpString = TRL("Group Tree");
	pa[n].pbValue = &pOptions->bGroupTree;
	pa[++n].lpString = TRL("Title");
	pa[n].pbValue = &pOptions->bTitle;
	pa[++n].lpString = TRL("User Name");
	pa[n].pbValue = &pOptions->bUserName;

	if(m_bDisallowPrintingPasswords == FALSE)
	{
		pa[++n].lpString = TRL("Password");
		pa[n].pbValue = &pOptions->bPassword;
	}
	else pOptions->bPassword = FALSE;
	
	pa[++n].lpString = TRL("URL");
	pa[n].pbValue = &pOptions->bURL;
	pa[++n].lpString = TRL("Notes");
	pa[n].pbValue = &pOptions->bNotes;
	pa[++n].lpString = TRL("Creation Time");
	pa[n].pbValue = &pOptions->bCreationTime;
	pa[++n].lpString = TRL("Last Access");
	pa[n].pbValue = &pOptions->bLastAccTime;
	pa[++n].lpString = TRL("Last Modification");
	pa[n].pbValue = &pOptions->bLastModTime;
	pa[++n].lpString = TRL("Expires");
	pa[n].pbValue = &pOptions->bExpireTime;
	pa[++n].lpString = TRL("Icon");
	pa[n].pbValue = &pOptions->bImage;
	pa[++n].lpString = TRL("UUID");
	pa[n].pbValue = &pOptions->bUUID;
	pa[++n].lpString = TRL("Attachment");
	pa[n].pbValue = &pOptions->bAttachment;*/

	/*if(bPrinting == TRUE)
	{
		dlg.m_strTitle = TRL("Print Options");
		dlg.m_strDescription = TRL("Here you can customize the printed sheet.");
	}
	else
	{
		dlg.m_strTitle = TRL("Export Options");
		dlg.m_strDescription = TRL("Here you can customize the exported files.");
	}

	if(bPrinting == TRUE)
	{
		ASSERT((n == (LCL_CHKOPT_PARAM_COUNT - 2)) || (n == (LCL_CHKOPT_PARAM_COUNT - 3)));
	}
	else { ASSERT(n == (LCL_CHKOPT_PARAM_COUNT - 1)); }*/
	/*dlg.m_dwNumParams = n + 1;
	dlg.m_pParams = (CHKOPT_PARAM *)pa;

	if(dlg.DoModal() == IDOK) { m_bDisplayDialog = FALSE; return TRUE; }*/
	m_bDisplayDialog = FALSE;
	return TRUE;
}

LRESULT CPasswordMgrUiHandler::OnExportTxt(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	CPwExport cExp; PWEXPORT_OPTIONS pwo;
	CString strFile;
	if(m_bFileOpen == FALSE) return 0L;
	
	cExp.SetManager(&m_mgr);
	cExp.SetNewLineSeq(TRUE);
	cExp.SetFormat(PWEXP_TXT);
	strFile = GetExportFile(PWEXP_TXT, NULL, FALSE);
	if(strFile.GetLength() != 0)
		if(GetExportOptions(&pwo, &cExp, FALSE) == TRUE)
			cExp.ExportAll(strFile, &pwo,&m_mgr);
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnExportHtml(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	CPwExport cExp; PWEXPORT_OPTIONS pwo;
	CString strFile;
	if(m_bFileOpen == FALSE) return 0L;
	
	cExp.SetManager(&m_mgr);
	cExp.SetNewLineSeq(TRUE);
	cExp.SetFormat(PWEXP_HTML);
	strFile = GetExportFile(PWEXP_HTML, NULL, FALSE);
	if(strFile.GetLength() != 0)
		if(GetExportOptions(&pwo, &cExp, FALSE) == TRUE)
			cExp.ExportAll(strFile, &pwo,&m_mgr);
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnExportXml(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	CPwExport cExp; PWEXPORT_OPTIONS pwo;
	CString strFile;
	if(m_bFileOpen == FALSE) return 0L;
	
	cExp.SetManager(&m_mgr);
	cExp.SetNewLineSeq(TRUE);
	cExp.SetFormat(PWEXP_XML);
	strFile = GetExportFile(PWEXP_XML, NULL, FALSE);
	if(strFile.GetLength() != 0)
		if(GetExportOptions(&pwo, &cExp, FALSE) == TRUE)
			cExp.ExportAll(strFile, &pwo,&m_mgr);
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnExportCsv(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	CPwExport cExp; PWEXPORT_OPTIONS pwo;
	CString strFile;
	if(m_bFileOpen == FALSE) return 0L;
	
	cExp.SetManager(&m_mgr);
	cExp.SetNewLineSeq(TRUE);
	cExp.SetFormat(PWEXP_CSV);
	strFile = GetExportFile(PWEXP_CSV, NULL, FALSE);
	if(strFile.GetLength() != 0)
		if(GetExportOptions(&pwo, &cExp, FALSE) == TRUE)
			cExp.ExportAll(strFile, &pwo,&m_mgr);
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnExportKeepass(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	return 0L;
}


LRESULT CPasswordMgrUiHandler::OnImportCWTxt(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	if(m_bFileOpen == FALSE) return 0L;
	if(m_nClassID == 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(113),BkString::Get(88));
		return 0L;
	}
	m_bDisplayDialog = TRUE;

	CString strFilter = _T("Text Files");
	strFilter += _T(" (*.txt)|*.txt|");
	strFilter += BkString::Get(1009);
	strFilter += _T(" (*.*)|*.*||");

	std::vector<std::basic_string<TCHAR> > vFiles = WU_GetFileNames(TRUE, _T("txt"),
		strFilter, TRUE, m_dlg->GetViewHWND(), FALSE, TRUE);

	for(size_t iFile = 0; iFile < vFiles.size(); ++iFile)
	{
		CPwImport pvi;
		pvi.m_dwLastGroupId = m_nClassID;
		pvi.m_nMasterId = m_nMasterID;
		if(pvi.ImportCWalletToDb(vFiles[iFile].c_str(), &m_mgr) == TRUE)
		{
			m_bModified = TRUE;
		}
		else
		{
			CString strMsg = vFiles[iFile].c_str();
			strMsg += _T("\r\n\r\n");
			strMsg += BkString::Get(142);
			CPkmpMsgBox2::Show (strMsg, BkString::Get(88), MB_ICONWARNING | MB_OK);
		}
	}

	m_bDisplayDialog = FALSE;
	return 0L;
}

LRESULT CPasswordMgrUiHandler::OnImportPVTxt(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	if(m_bFileOpen == FALSE) return 0L;
	if(m_nClassID == 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(113),BkString::Get(88));
		return 0L;
	}
	m_bDisplayDialog = TRUE;

	CString strFilter = _T("Text Files");
	strFilter += _T(" (*.txt)|*.txt|");
	strFilter += BkString::Get(1009);
	strFilter += _T(" (*.*)|*.*||");

	std::vector<std::basic_string<TCHAR> > vFiles = WU_GetFileNames(TRUE, _T("txt"),
		strFilter, TRUE, m_dlg->GetViewHWND(), FALSE, TRUE);

	for(size_t iFile = 0; iFile < vFiles.size(); ++iFile)
	{
		CPwImport pvi;
		pvi.m_dwLastGroupId = m_nClassID;
		pvi.m_nMasterId = m_nMasterID;
		if(pvi.ImportPVaultToDb(vFiles[iFile].c_str(), &m_mgr) == TRUE)
		{
			m_bModified = TRUE;
		}
		else
		{
			CString strMsg = vFiles[iFile].c_str();
			strMsg += _T("\r\n\r\n");
			strMsg += BkString::Get(142);
			CPkmpMsgBox2::Show (strMsg, BkString::Get(88), MB_ICONWARNING | MB_OK);
		}
	}

	m_bDisplayDialog = FALSE;
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnImportCsv(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	if(m_bFileOpen == FALSE) return 0L;
	if(m_nClassID == 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(113),BkString::Get(88));
		return 0L;
	}
	m_bDisplayDialog = TRUE;

	CString strFilter = _T("Text Files");
	strFilter += _T(" (*.txt)|*.txt|");
	strFilter += BkString::Get(1009);
	strFilter += _T(" (*.*)|*.*||");

	std::vector<std::basic_string<TCHAR> > vFiles = WU_GetFileNames(TRUE, _T("txt"),
		strFilter, TRUE, m_dlg->GetViewHWND(), FALSE, TRUE);

	for(size_t iFile = 0; iFile < vFiles.size(); ++iFile)
	{
		CPwImport pvi;
		pvi.m_dwLastGroupId = m_nClassID;
		pvi.m_nMasterId = m_nMasterID;
		if(pvi.ImportCsvToDb(vFiles[iFile].c_str(), &m_mgr) == TRUE)
		{
			m_bModified = TRUE;
		}
		else
		{
			CString strMsg = vFiles[iFile].c_str();
			strMsg += _T("\r\n\r\n");
			strMsg += BkString::Get(142);
			CPkmpMsgBox2::Show (strMsg, BkString::Get(88), MB_ICONWARNING | MB_OK);
		}
	}

	m_bDisplayDialog = FALSE;
	return 0L;
}
LRESULT CPasswordMgrUiHandler::OnImportKeepass(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	NotifyUserActivity();
	if(m_bFileOpen == FALSE) return 0L;
	if(m_nClassID == 0)
	{
		CPkmpMsgBox2::Show(BkString::Get(113),BkString::Get(88));
		return 0L;
	}
	m_bDisplayDialog = TRUE;

	CString strFilter = _T("Text Files");
	strFilter += _T(" (*.txt)|*.txt|");
	strFilter += BkString::Get(1009);
	strFilter += _T(" (*.*)|*.*||");

	std::vector<std::basic_string<TCHAR> > vFiles = WU_GetFileNames(TRUE, _T("txt"),
		strFilter, TRUE, m_dlg->GetViewHWND(), FALSE, TRUE);

	for(size_t iFile = 0; iFile < vFiles.size(); ++iFile)
	{
		CPwImport pvi;
		pvi.m_nMasterId = m_nMasterID;
		if(pvi.ImportPwSafeToDb(vFiles[iFile].c_str(), &m_mgr,m_nClassID) == TRUE)
		{
			m_bModified = TRUE;
		}
		else
		{
			CString strMsg = vFiles[iFile].c_str();
			strMsg += _T("\r\n\r\n");
			strMsg += BkString::Get(142);
			CPkmpMsgBox2::Show (strMsg, BkString::Get(88), MB_ICONWARNING | MB_OK);
		}
	}

	m_bDisplayDialog = FALSE;
	return 0L;
}

void CPasswordMgrUiHandler::OnTimer(UINT_PTR nIDEvent)
{
	if(nIDEvent == APPWND_TIMER_ID)
	{
		if(thePrefs.m_PswSettings.Clear_Clipboard && m_nClipboardCountdown != -1)
		{
			--m_nClipboardCountdown;

			if(m_nClipboardCountdown == -1)
			{
				m_dlg->SetStatusPanel1(BkString::Get(143));
				ClearClipboardIfOwner();
			}
			else if(m_nClipboardCountdown == 0)
				m_dlg->SetStatusPanel1(BkString::Get(144));
			else
			{
				CString str;
				str.Format(BkString::Get(145), m_nClipboardCountdown);
				m_dlg->SetStatusPanel1(str);
			}
		}
		if((m_bLocked == FALSE) && (m_bFileOpen == TRUE) && (m_bDisplayDialog == FALSE))
		{
			if(thePrefs.m_PswSettings.Lock_When_Idle && m_nLockTimeDef != -1)
			{
				const UINT64 uCurTimeUtc = _GetCurrentTimeUtc();
				if(uCurTimeUtc >= m_uLockAt)
				{
					OnBtnAccountLock();
				}
				
				// }
			}
		}
	}
}

void CPasswordMgrUiHandler::OnSize(UINT nType, CSize size)
{
	NotifyUserActivity();
	
	BOOL bWasInvisible = FALSE;
	if(m_bMinimized == TRUE) bWasInvisible = TRUE;

	if(nType == SIZE_MAXIMIZED) m_bWasMaximized = TRUE;
	else 
	{
		if((nType == SIZE_RESTORED) && (m_bWasMaximized == TRUE)) m_bWasMaximized = FALSE;
		else if((nType == SIZE_RESTORED) && (m_bMinimized == FALSE)) m_bWasMaximized = FALSE;
	}

	if(nType == SIZE_MINIMIZED) m_bMinimized = TRUE;
	else if((nType == SIZE_RESTORED) && (m_bMinimized == TRUE)) m_bMinimized = FALSE;
	else if((nType == SIZE_MAXIMIZED) && (m_bMinimized == TRUE)) m_bMinimized = FALSE;

	if(m_bIgnoreSizeEvent == TRUE) return;

	

	BOOL m_bRestore = FALSE;

	if(((nType == SIZE_RESTORED) || (nType == SIZE_MAXIMIZED)) &&
		(bWasInvisible == TRUE))
	{
		_ChangeLockState(FALSE);
	}
	else if(nType == SIZE_MINIMIZED)
	{
		if(thePrefs.m_PswSettings.Lock_When_Min == TRUE)
		{
			_ChangeLockState(TRUE); // Lock

			// Was the locking successful? If not: restore window
			if((m_bFileOpen == TRUE) && (m_bLocked == FALSE)) m_bRestore = TRUE;
		}
	}

	
	SetMsgHandled( FALSE );
}
void CPasswordMgrUiHandler::_ChangeLockState(BOOL bLocked)
{
	if((bLocked == TRUE) && (m_bLocked == FALSE)) // Should lock
		OnBtnAccountLock();
	else if((bLocked == FALSE) && (m_bLocked == TRUE)) // Should unlock
		OnBtnAccountLock();
}
inline UINT64 CPasswordMgrUiHandler::_GetCurrentTimeUtc()
{
	FILETIME ft;
	GetSystemTimeAsFileTime(&ft);

	return ((static_cast<UINT64>(ft.dwHighDateTime) << 32) |
		static_cast<UINT64>(ft.dwLowDateTime));
}

inline void CPasswordMgrUiHandler::_SetAutoLockTimeout(long lSeconds)
{
	m_uLockAt = (_GetCurrentTimeUtc() + (static_cast<UINT64>(lSeconds) *
		0x989680ui64)); // 10000000
}

void CPasswordMgrUiHandler::NotifyUserActivity()
{
	// m_nLockCountdown = m_nLockTimeDef;

	if(m_nLockTimeDef < 0) m_uLockAt = UINT64_MAX;
	else _SetAutoLockTimeout(m_nLockTimeDef);
}

LRESULT CPasswordMgrUiHandler::OnSettingChanged(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	CString szTemp = thePrefs.m_PswSettings.Genp_Profile ;// ini.GetString(PWMKEY_GENPROFILEAUTO);
	if(szTemp.GetLength() > 0)
	{
		std::basic_string<TCHAR> strAutoProfile = szTemp;
		PwgStringToProfile(strAutoProfile, &m_pgsAutoProfile);
	}
	else PwgGetDefaultProfile(&m_pgsAutoProfile);

	m_nLockTimeDef = thePrefs.m_PswSettings.Idle_Second ;
	SetMsgHandled( FALSE );
	return 0L;
}